/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package estep;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;

/**
 *
 * @author Printer
 */
public class EStepWindow extends javax.swing.JFrame implements SerialPortEventListener {

    /**
     * Creates new form EStepWindow
     */
    public String PORT_NAMES[];
    ArrayList<String> portHolder = new ArrayList<String>();
    SerialPort serialPort;
    private InputStream input;
    private OutputStream output;
    private static final int TIME_OUT = 2000;
    private static final int DATA_RATE = 9600;
    CommPortIdentifier portId = null;
    ArrayList<String> serialLines = new ArrayList<String>();

    public EStepWindow() {
        initComponents();
        initialize();
    }

    public void initialize() {

        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
        int portSize = 0;
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            System.out.println(currPortId.getName());
            portHolder.add(currPortId.getName());
            portSize++;
        }
        PORT_NAMES = new String[portSize];
        for (int i = 0; i < portHolder.size(); i++) {
            PORT_NAMES[i] = portHolder.get(i);
        }
        portList.setListData(PORT_NAMES);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        portList = new javax.swing.JList();
        getPortButton = new javax.swing.JButton();
        selectPortButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        serialTextArea = new javax.swing.JTextArea();
        jSeparator1 = new javax.swing.JSeparator();
        advanceButton = new javax.swing.JButton();
        retractButton = new javax.swing.JButton();
        advanceSpinner = new javax.swing.JSpinner();
        retractSpinner = new javax.swing.JSpinner();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        jScrollPane2 = new javax.swing.JScrollPane();
        stepperSelect = new javax.swing.JList();
        serialClear = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        saveStateButton = new javax.swing.JButton();
        clearStateButton = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        EEPROMTextArea = new javax.swing.JTextArea();
        readStateButton = new javax.swing.JButton();
        clearSelMotButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jScrollPane4.setViewportView(portList);

        getPortButton.setText("Get Ports");
        getPortButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                getPortButtonActionPerformed(evt);
            }
        });

        selectPortButton.setText("Select Port");
        selectPortButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectPortButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(selectPortButton, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(getPortButton, javax.swing.GroupLayout.PREFERRED_SIZE, 348, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane4))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(selectPortButton, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)
                    .addComponent(getPortButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        jTabbedPane1.addTab("Ports", jPanel2);

        serialTextArea.setColumns(20);
        serialTextArea.setRows(5);
        jScrollPane1.setViewportView(serialTextArea);

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);

        advanceButton.setText("Advance");
        advanceButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                advanceButtonActionPerformed(evt);
            }
        });

        retractButton.setText("Retract");
        retractButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                retractButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("[mm]");

        jLabel3.setText("[mm]");

        stepperSelect.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Stepper 1", "Stepper 2", "Stepper 3", "Stepper 4", "Stepper 5", "Stepper 6" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(stepperSelect);

        serialClear.setText("Clear Serial Monitor");
        serialClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                serialClearActionPerformed(evt);
            }
        });

        jLabel4.setText("EEPROM");

        saveStateButton.setText("Save States");
        saveStateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveStateButtonActionPerformed(evt);
            }
        });

        clearStateButton.setText("Clear States");
        clearStateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearStateButtonActionPerformed(evt);
            }
        });

        EEPROMTextArea.setColumns(20);
        EEPROMTextArea.setRows(5);
        jScrollPane3.setViewportView(EEPROMTextArea);

        readStateButton.setText("Read States");
        readStateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                readStateButtonActionPerformed(evt);
            }
        });

        clearSelMotButton.setText("Clear Selected Motor");
        clearSelMotButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearSelMotButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(serialClear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(saveStateButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(readStateButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(clearStateButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(clearSelMotButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane3))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(retractButton, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(retractSpinner))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(advanceButton, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(advanceSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3)))
                            .addComponent(jLabel4))
                        .addGap(0, 4, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jSeparator1)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(serialClear)
                        .addGap(8, 8, 8))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(advanceButton, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(advanceSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel2)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(retractButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(retractSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel3)))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 3, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(clearStateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(saveStateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(readStateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(clearSelMotButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 68, Short.MAX_VALUE))
                            .addComponent(jScrollPane3))
                        .addContainerGap())))
        );

        jTabbedPane1.addTab("Control", jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void selectPortButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectPortButtonActionPerformed
        try {

            Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();


            while (portEnum.hasMoreElements()) {
                CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
                if (currPortId.getName().equalsIgnoreCase((String) portList.getSelectedValue())) {
                    portId = currPortId;
                }
            }

            if (portId == null) {
                System.out.println("Could not find port.");
                return;
            }

            serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);

            serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);

            input = serialPort.getInputStream();
            output = serialPort.getOutputStream();

            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }//GEN-LAST:event_selectPortButtonActionPerformed

    private void getPortButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getPortButtonActionPerformed
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
        int portSize = 0;
        portHolder.clear();
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            System.out.println(currPortId.getName());
            portHolder.add(currPortId.getName());
            portSize++;
        }
        PORT_NAMES = new String[portSize];
        for (int i = 0; i < portHolder.size(); i++) {
            PORT_NAMES[i] = portHolder.get(i);
        }
        portList.setListData(PORT_NAMES);
    }//GEN-LAST:event_getPortButtonActionPerformed

    public String convertName(String name) {
        if (name.contains("1")) {
            return "s1";
        }

        if (name.contains("2")) {
            return "s2";
        }

        if (name.contains("3")) {
            return "s3";
        }

        if (name.contains("4")) {
            return "s4";
        }

        if (name.contains("5")) {
            return "s5";
        }

        if (name.contains("6")) {
            return "s6";
        }
        return null;
    }
    private void advanceButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_advanceButtonActionPerformed
        if (output != null) {
            if (stepperSelect.getSelectedIndex() != -1) {

                try {
                    String toSend = "advance:" + convertName(((String) stepperSelect.getSelectedValue())) + ":" + (int) advanceSpinner.getValue() + " <Sent>";
                    output.write(toSend.getBytes());
                } catch (IOException ex) {
                    Logger.getLogger(EStepWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                System.out.println("Please select a motor");
                serialTextArea.append("Please select a motor" + "\n");

            }
        } else {
            System.out.println("Please select and open a port first");
            serialTextArea.append("Please select and open a port first" + "\n");


        }
    }//GEN-LAST:event_advanceButtonActionPerformed

    private void retractButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_retractButtonActionPerformed
        if (output != null) {

            if (stepperSelect.getSelectedIndex() != -1) {

                try {
                    String toSend = "retract:" + convertName(((String) stepperSelect.getSelectedValue())) + ":" + (int) retractSpinner.getValue() + " <Sent>";
                    output.write(toSend.getBytes());
                } catch (IOException ex) {
                    Logger.getLogger(EStepWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                System.out.println("Please select a motor");
                serialTextArea.append("Please select a motor" + "\n");

            }
        } else {
            System.out.println("Please select and open a port first");
            serialTextArea.append("Please select and open a port first" + "\n");


        }
    }//GEN-LAST:event_retractButtonActionPerformed

    private void serialClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_serialClearActionPerformed
        serialTextArea.setText("");
    }//GEN-LAST:event_serialClearActionPerformed

    private void saveStateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveStateButtonActionPerformed
        try {
            String toSend = "write:all:steps";

            output.write(toSend.getBytes());
        } catch (IOException ex) {
            Logger.getLogger(EStepWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_saveStateButtonActionPerformed

    private void readStateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_readStateButtonActionPerformed
        try {
            String toSend = "read:all:steps";
            EEPROMTextArea.setText("");
            output.write(toSend.getBytes());
        } catch (IOException ex) {
            Logger.getLogger(EStepWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_readStateButtonActionPerformed

    private void clearStateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearStateButtonActionPerformed
        try {
            String toSend = "erase:all:steps";
            //EEPROMTextArea.setText("");
            output.write(toSend.getBytes());
        } catch (IOException ex) {
            Logger.getLogger(EStepWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_clearStateButtonActionPerformed

    private void clearSelMotButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearSelMotButtonActionPerformed
        if (output != null) {

            if (stepperSelect.getSelectedIndex() != -1) {

                try {
                    String toSend = "erase:motor:" + convertName(((String) stepperSelect.getSelectedValue())) + " <Sent>";
                    output.write(toSend.getBytes());
                } catch (IOException ex) {
                    Logger.getLogger(EStepWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                System.out.println("Please select a motor");
                serialTextArea.append("Please select a motor" + "\n");

            }
        } else {
            System.out.println("Please select and open a port first");
            serialTextArea.append("Please select and open a port first" + "\n");


        }

    }//GEN-LAST:event_clearSelMotButtonActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        try {
            serialPort.close();
            input.close();
            output.close();
        } catch (IOException ex) {
            Logger.getLogger(EStepWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formWindowClosed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EStepWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EStepWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EStepWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EStepWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new EStepWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea EEPROMTextArea;
    private javax.swing.JButton advanceButton;
    private javax.swing.JSpinner advanceSpinner;
    private javax.swing.JButton clearSelMotButton;
    private javax.swing.JButton clearStateButton;
    private javax.swing.JButton getPortButton;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JList portList;
    private javax.swing.JButton readStateButton;
    private javax.swing.JButton retractButton;
    private javax.swing.JSpinner retractSpinner;
    private javax.swing.JButton saveStateButton;
    private javax.swing.JButton selectPortButton;
    private javax.swing.JButton serialClear;
    private javax.swing.JTextArea serialTextArea;
    private javax.swing.JList stepperSelect;
    // End of variables declaration//GEN-END:variables

    public void moveEEPROM() throws BadLocationException {
        // EEPROMTextArea.setText("");
        serialLines.clear();
        String text = serialTextArea.getText();
        int lineCount = serialTextArea.getLineCount();
        for (int i = 0; i < lineCount; i++) {
            int start = serialTextArea.getLineStartOffset(i);
            int end = serialTextArea.getLineEndOffset(i);
            String line = text.substring(start, end);
            // System.out.println(line);
            serialLines.add(line);
        }

        checkForEELines();
    }

    public void checkForEELines() {
        //EEPROMTextArea.setText("");
        ArrayList<String> justSerial = new ArrayList<String>();


        for (int i = 0; i < serialLines.size(); i++) {
            if (serialLines.get(i).startsWith("S") && serialLines.get(i).contains("mm")) {
                if (serialLines.get(i).contains("\n")) {
                    EEPROMTextArea.append(serialLines.get(i));
                } else {
                    EEPROMTextArea.append(serialLines.get(i) + "\n");

                }
            } else {
                if (!serialLines.get(i).equals("\n")) {
                    if (!serialLines.get(i).equals("") && !serialLines.get(i).equals(" ")) {
                        justSerial.add(serialLines.get(i));
                    }
                }
            }
        }


        serialTextArea.setText("");

        for (int i = 0; i < justSerial.size(); i++) {
            serialTextArea.append(justSerial.get(i));
            System.out.println(i + justSerial.get(i));
        }

        serialLines.clear();


    }

    public void processMessage(String message) {
        serialTextArea.append(message);
        try {
            moveEEPROM();
        } catch (BadLocationException ex) {
            Logger.getLogger(EStepWindow.class.getName()).log(Level.SEVERE, null, ex);
        }

        serialTextArea.setCaretPosition(serialTextArea.getText().length());
    }

    public void serialEvent(SerialPortEvent spe) {
        try {
            String message = "";
            while (input.available() > 0) {

                message += (char) (input.read());
                // System.out.print();
            }
            processMessage(message);
            //  serialTextArea.append(message);
        } catch (IOException ex) {
            Logger.getLogger(EStepWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
